import { Button, Form, Input, Toast } from "antd-mobile";
import { useNavigate, useSearchParams } from "react-router-dom";
import "./Login.scss";
import { useState } from "react";
import { EyeInvisibleOutline, EyeOutline } from "antd-mobile-icons";
import { Helmet } from "react-helmet-async";
import { setToken } from "@/utils/auth";
import { login } from "@/api/user";

interface LoginProps {
  username: string;
  password: string;
}

export default function Login() {
  const [params] = useSearchParams();
  const navigate = useNavigate();
  const redirect = params.get("redirect") || "/";

  const [visible, setVisible] = useState(false);

  const finish = async (value: LoginProps) => {
    const { data } = await login(value.username, value.password);
    setToken(data.token);
    navigate(redirect, { replace: true });
  };
  return (
    <div className="h-screen w-screen flex items-center justify-center bg-gray-50">
      <Helmet>
        <title>登录</title>
      </Helmet>
      <div className="w-11/12 shadow-lg bg-white rounded-lg min-h-36 p-4">
        <h2 className="text-2xl font-bold text-center text-gray-600">登 录</h2>
        <Form
          layout="horizontal"
          onFinish={finish}
          footer={
            <div>
              <Button block color="primary" size="large" type="submit">
                登录
              </Button>
            </div>
          }
        >
          {/* 隐藏的欺骗字段（绕过浏览器自动填充） */}
          <div style={{ display: "none" }}>
            <input type="text" name="fake-username" autoComplete="username" />
            <input
              type="password"
              name="fake-password"
              autoComplete="current-password"
            />
          </div>
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: "用户名不得为空" }]}
          >
            <Input placeholder="请输入用户名" autoComplete="off" />
          </Form.Item>
          <Form.Item
            name="password"
            label="密 码"
            rules={[
              { required: true, message: "密码不得为空" },
              { min: 6, message: "密码不得低于6位" },
            ]}
          >
            <div className="password">
              <Input
                className="input"
                placeholder="请输入密码"
                type={visible ? "text" : "password"}
                autoComplete="new-password"
              />
              <div className="eye">
                {visible ? (
                  <EyeInvisibleOutline onClick={() => setVisible(false)} />
                ) : (
                  <EyeOutline onClick={() => setVisible(true)} />
                )}
              </div>
            </div>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
